package com.itrip.log.module.web;

import java.util.concurrent.CopyOnWriteArrayList;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.webbitserver.BaseWebSocketHandler;
import org.webbitserver.WebServer;
import org.webbitserver.WebServers;
import org.webbitserver.WebSocketConnection;

import com.itrip.log.core.BootstrapServer;
import com.itrip.log.core.ReaderBean;
import com.itrip.log.module.handler.ILogHandler;
import com.itrip.log.util.Config;

/**
 * Function:websocket服务类
 *
 * @date:2016年7月8日/下午9:32:27
 * @Author:coder_czp@126.com
 * @version:1.0
 */
@Controller
public class WSServer extends BaseWebSocketHandler implements ILogHandler {

	private static CopyOnWriteArrayList<WebSocketConnection> conns = new CopyOnWriteArrayList<WebSocketConnection>();
	private static Logger LOG = LoggerFactory.getLogger(WSServer.class);

	@PostConstruct
	public void start() {
		int wsPort = Config.getInt("ws_port", 9090);
		String pathCfg = Config.getString("ws_path", "/ws");
		WebServer webServer = WebServers.createWebServer(wsPort).add(pathCfg, this);
		webServer.start();
		LOG.info("Server running at {}", webServer.getUri());
	}

	public void onOpen(WebSocketConnection connection) {
		connection.send("Hello! There are " + conns.size() + " other connections active");
		LOG.info("add connectionCount {}", conns.size());
		conns.add(connection);
	}

	public void onClose(WebSocketConnection connection) {
		LOG.info("del connectionCount {}", connection);
		conns.remove(connection);
	}

	public void onMessage(WebSocketConnection connection, String message) {
		connection.send(message.toUpperCase());
	}

	public static void send(String info) {
		for (WebSocketConnection ws : conns) {
			ws.send(info);
		}
	}

	@Override
	public void handle(ReaderBean bean) {
		send(bean.getLine());
	}

	@Override
	public boolean match(String file) {
		return true;
	}

	@Override
	public void setBoostServer(BootstrapServer server) {
		
	}

	@Override
	public void stop() {
		
	}
}
